<template>
  <div class="login-page">
    <div class="login-container">
      <!-- 登录背景 -->
      <div class="login-background">
        <div class="bg-overlay"></div>
        <div class="bg-content">
          <div class="system-logo">
            <i class="fas fa-hard-hat"></i>
            <h1>矿山安全评价系统</h1>
            <p>Mine Safety Evaluation System</p>
          </div>
          <div class="feature-list">
            <div class="feature-item">
              <i class="fas fa-shield-alt"></i>
              <span>安全评价</span>
            </div>
            <div class="feature-item">
              <i class="fas fa-exclamation-triangle"></i>
              <span>隐患跟踪</span>
            </div>
            <div class="feature-item">
              <i class="fas fa-file-alt"></i>
              <span>报告管理</span>
            </div>
            <div class="feature-item">
              <i class="fas fa-book"></i>
              <span>知识库</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 登录表单 -->
      <div class="login-form-container">
        <div class="login-form">
          <div class="form-header">
            <h2>系统登录</h2>
            <p>请使用您的账号登录系统</p>
          </div>

          <form @submit.prevent="handleLogin" class="form-content">
            <div class="form-group">
              <label>
                <i class="fas fa-user"></i>
                用户名
              </label>
              <input
                type="text"
                v-model="loginForm.username"
                placeholder="请输入用户名"
                required
                :disabled="isLoading"
                class="form-input"
              />
            </div>

            <div class="form-group">
              <label>
                <i class="fas fa-lock"></i>
                密码
              </label>
              <div class="password-input">
                <input
                  :type="showPassword ? 'text' : 'password'"
                  v-model="loginForm.password"
                  placeholder="请输入密码"
                  required
                  :disabled="isLoading"
                  class="form-input"
                />
                <button
                  type="button"
                  @click="showPassword = !showPassword"
                  class="password-toggle"
                  :disabled="isLoading"
                >
                  <i class="fas" :class="showPassword ? 'fa-eye-slash' : 'fa-eye'"></i>
                </button>
              </div>
            </div>

            <div class="form-group">
              <label class="checkbox-label">
                <input
                  type="checkbox"
                  v-model="loginForm.rememberMe"
                  :disabled="isLoading"
                />
                <span class="checkmark"></span>
                记住我
              </label>
            </div>

            <button 
              type="submit" 
              class="login-btn"
              :disabled="!isFormValid || isLoading"
            >
              <i class="fas" :class="isLoading ? 'fa-spinner fa-spin' : 'fa-sign-in-alt'"></i>
              {{ isLoading ? '登录中...' : '登录' }}
            </button>

            <div class="form-footer">
              <button 
                type="button" 
                class="create-admin-btn"
                @click="showRegister = true"
                :disabled="isLoading"
              >
                <i class="fas fa-user-plus"></i>
                用户注册（测试）
              </button>
            </div>
          </form>
        </div>

        <!-- 系统信息 -->
        <div class="system-info">
          <p>© 2025 矿山安全评价系统 版权所有</p>
          <p>Version 1.0.0</p>
        </div>
      </div>
    </div>

    <!-- 帮助对话框 -->
    <div v-if="showHelpDialog" class="modal-overlay" @click="showHelpDialog = false">
      <div class="modal-content help-modal" @click.stop>
        <div class="modal-header">
          <h3><i class="fas fa-question-circle"></i> 登录帮助</h3>
          <button class="modal-close" @click="showHelpDialog = false">
            <i class="fas fa-times"></i>
          </button>
        </div>
        <div class="modal-body">
          <div class="help-content">
            <h4>账号问题</h4>
            <p>如果您忘记了登录密码，请联系系统管理员重置密码。</p>
            
            <h4>默认账号</h4>
            <div class="account-info">
              <p><strong>管理员账号：</strong> admin</p>
              <p><strong>默认密码：</strong> admin123</p>
            </div>
            
            <h4>联系方式</h4>
            <p>技术支持：400-xxx-xxxx</p>
            <p>邮箱：support@minesystem.com</p>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-primary" @click="showHelpDialog = false">我知道了</button>
        </div>
      </div>
    </div>

    <!-- 用户注册对话框 -->
    <div v-if="showRegister" class="modal-overlay" @click="showRegister = false">
      <div class="modal-content create-admin-modal" @click.stop>
        <div class="modal-header">
          <h3><i class="fas fa-user-plus"></i> 用户注册</h3>
          <button class="modal-close" @click="showRegister = false">
            <i class="fas fa-times"></i>
          </button>
        </div>
        <div class="modal-body">
          <form @submit.prevent="handleRegister" class="create-admin-form">
            <div class="form-group">
              <label>注册角色 *</label>
              <div class="radio-group">
                <label class="radio-label">
                  <input type="radio" v-model="registerForm.type" value="employee">
                  普通员工
                </label>
                <label class="radio-label">
                  <input type="radio" v-model="registerForm.type" value="safety">
                  安全员
                </label>
                <label class="radio-label">
                  <input type="radio" v-model="registerForm.type" value="admin">
                  管理员
                </label>
              </div>
            </div>

            <div class="form-group">
              <label>用户名 *</label>
              <input
                type="text"
                v-model="registerForm.username"
                placeholder="请输入用户名（必填）"
                required
                class="form-input"
              />
            </div>

            <div class="form-group">
              <label>密码 *</label>
              <input
                type="password"
                v-model="registerForm.password"
                placeholder="请输入密码（必填）"
                required
                class="form-input"
              />
            </div>

            <div class="form-group">
              <label>姓名</label>
              <input
                type="text"
                v-model="registerForm.name"
                placeholder="请输入姓名（可选）"
                class="form-input"
              />
            </div>

            <div class="form-group">
              <label>手机号</label>
              <input
                type="tel"
                v-model="registerForm.phone"
                placeholder="请输入手机号（可选）"
                class="form-input"
              />
            </div>

            <div class="form-group">
              <label>邮箱</label>
              <input
                type="email"
                v-model="registerForm.email"
                placeholder="请输入邮箱（可选）"
                class="form-input"
              />
            </div>
          </form>
        </div>
        <div class="modal-footer">
          <button class="btn btn-secondary" @click="showRegister = false" :disabled="isLoading">取消</button>
          <button class="btn btn-primary" @click="handleRegister" :disabled="isLoading">
            <i class="fas" :class="isLoading ? 'fa-spinner fa-spin' : 'fa-check'"></i>
            {{ isLoading ? '注册中...' : '注册' }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../stores/user'
import { api } from '../api/index'

const router = useRouter()
const userStore = useUserStore()

// 表单数据
const loginForm = ref({
  username: '',
  password: '',
  rememberMe: false
})

// 状态管理
const isLoading = ref(false)
const showPassword = ref(false)
const showHelpDialog = ref(false)
const showRegister = ref(false)

// 注册表单
const registerForm = ref({
  type: 'employee',
  username: '',
  password: '',
  name: '',
  phone: '',
  email: ''
})

// 计算属性
const isFormValid = computed(() => {
  return loginForm.value.username.trim() && loginForm.value.password.trim()
})

// 登录处理
const handleLogin = async () => {
  if (!isFormValid.value) return

  try {
    isLoading.value = true
    
    // 调用登录API
    const response = await api.user.login({
      username: loginForm.value.username.trim(),
      password: loginForm.value.password
    })

    if (response.status === 'success') {
      // 更新用户store
      await userStore.login(response.data)
      
      // 显示成功提示
      showNotification('登录成功！', 'success')
      
      // 跳转到用户管理页面
      setTimeout(() => {
        router.push('/users')
      }, 1000)
    } else {
      showNotification(response.message || '登录失败，请检查用户名和密码', 'error')
    }
  } catch (error) {
    console.error('登录错误:', error)
    showNotification('登录失败，请检查网络连接后重试', 'error')
  } finally {
    isLoading.value = false
  }
}

// 用户注册
const handleRegister = async () => {
  // 仅验证用户名和密码为必填
  if (!registerForm.value.username || !registerForm.value.password) {
    showNotification('请填写用户名和密码', 'warning')
    return
  }

  try {
    isLoading.value = true
    
    const response = await api.user.create({
      ...registerForm.value
    })

    if (response.status === 'success') {
      showNotification('用户注册成功！', 'success')
      
      // 清空表单
      registerForm.value = {
        type: 'employee',
        username: '',
        password: '',
        name: '',
        phone: '',
        email: ''
      }
      
      // 关闭对话框
      showRegister.value = false
      
      // 自动填充登录表单
      loginForm.value.username = response.data.username
    } else {
      showNotification(response.message || '用户注册失败', 'error')
    }
  } catch (error) {
    console.error('用户注册错误:', error)
    showNotification('用户注册失败，请稍后重试', 'error')
  } finally {
    isLoading.value = false
  }
}

// 显示通知
const showNotification = (message: string, type: 'success' | 'error' | 'warning' | 'info' = 'info') => {
  // 创建通知元素
  const notification = document.createElement('div')
  notification.className = `notification ${type}`
  notification.textContent = message
  
  // 设置样式
  const colors = {
    success: '#27ae60',
    error: '#e74c3c', 
    warning: '#f39c12',
    info: '#3498db'
  }
  
  notification.style.cssText = `
    position: fixed;
    top: 20px;
    right: 20px;
    background: white;
    padding: 15px 20px;
    border-radius: 8px;
    box-shadow: 0 4px 20px rgba(0,0,0,0.1);
    z-index: 3000;
    border-left: 4px solid ${colors[type]};
    animation: slideIn 0.3s ease;
    max-width: 300px;
    font-size: 14px;
  `
  
  document.body.appendChild(notification)
  
  // 3秒后自动移除
  setTimeout(() => {
    if (notification.parentNode) {
      notification.remove()
    }
  }, 3000)
}

// 页面挂载时检查登录状态
onMounted(() => {
  // 如果已经登录，直接跳转
  if (userStore.userInfo.id) {
    router.push('/users')
  }
  
  // 添加键盘快捷键
  const handleKeyPress = (event: KeyboardEvent) => {
    if (event.key === 'Enter' && isFormValid.value && !isLoading.value) {
      handleLogin()
    }
  }
  
  document.addEventListener('keypress', handleKeyPress)
  
  // 组件卸载时移除事件监听
  onUnmounted(() => {
    document.removeEventListener('keypress', handleKeyPress)
  })
})
</script>

<style scoped>
.login-page {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  position: relative;
  overflow: hidden;
}

.login-page::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: url('/bg1.png') center/cover no-repeat;
  opacity: 0.1;
  z-index: 0;
}

.login-container {
  display: flex;
  width: 100%;
  max-width: 1200px;
  min-height: 600px;
  background: white;
  border-radius: 20px;
  box-shadow: 0 25px 80px rgba(0, 0, 0, 0.3);
  overflow: hidden;
  position: relative;
  z-index: 1;
}

/* 登录背景区域 */
.login-background {
  flex: 1;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  text-align: center;
  padding: 60px 40px;
}

.bg-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.1);
}

.bg-content {
  position: relative;
  z-index: 1;
}

.system-logo {
  margin-bottom: 40px;
}

.system-logo i {
  font-size: 64px;
  margin-bottom: 20px;
  display: block;
}

.system-logo h1 {
  font-size: 32px;
  font-weight: 600;
  margin: 0 0 10px 0;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}

.system-logo p {
  font-size: 16px;
  opacity: 0.9;
  margin: 0;
  font-weight: 300;
}

.feature-list {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
  max-width: 300px;
  margin: 0 auto;
}

.feature-item {
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 14px;
  opacity: 0.9;
}

.feature-item i {
  font-size: 18px;
  width: 24px;
}

/* 登录表单区域 */
.login-form-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  padding: 60px 40px 40px;
  background: #fafbfc;
}

.login-form {
  width: 100%;
  max-width: 400px;
  margin: 0 auto;
}

.form-header {
  text-align: center;
  margin-bottom: 40px;
}

.form-header h2 {
  font-size: 28px;
  font-weight: 600;
  color: #2c3e50;
  margin: 0 0 10px 0;
}

.form-header p {
  color: #6c757d;
  margin: 0;
  font-size: 14px;
}

.form-content {
  width: 100%;
}

.form-group {
  margin-bottom: 24px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 600;
  color: #495057;
  font-size: 14px;
}

.form-group label i {
  margin-right: 8px;
  color: #6c757d;
  width: 16px;
}

.form-input {
  width: 100%;
  padding: 14px 16px;
  border: 2px solid #e9ecef;
  border-radius: 12px;
  font-size: 16px;
  transition: all 0.3s ease;
  background: white;
  box-sizing: border-box;
}

.form-input:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.form-input:disabled {
  background: #f8f9fa;
  cursor: not-allowed;
}

.password-input {
  position: relative;
}

.password-toggle {
  position: absolute;
  right: 12px;
  top: 50%;
  transform: translateY(-50%);
  background: none;
  border: none;
  color: #6c757d;
  cursor: pointer;
  padding: 8px;
  border-radius: 4px;
  transition: all 0.3s ease;
}

.password-toggle:hover:not(:disabled) {
  color: #495057;
  background: #f8f9fa;
}

.password-toggle:disabled {
  cursor: not-allowed;
  opacity: 0.5;
}

.checkbox-label {
  display: flex;
  align-items: center;
  cursor: pointer;
  user-select: none;
  font-weight: 400;
}

.checkbox-label input[type="checkbox"] {
  display: none;
}

.checkmark {
  width: 18px;
  height: 18px;
  border: 2px solid #dee2e6;
  border-radius: 4px;
  margin-right: 10px;
  position: relative;
  transition: all 0.3s ease;
}

.checkbox-label input[type="checkbox"]:checked + .checkmark {
  background: #667eea;
  border-color: #667eea;
}

.checkbox-label input[type="checkbox"]:checked + .checkmark::after {
  content: '✓';
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  color: white;
  font-size: 12px;
  font-weight: bold;
}

.login-btn {
  width: 100%;
  padding: 16px;
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: white;
  border: none;
  border-radius: 12px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  margin-bottom: 20px;
}

.login-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(102, 126, 234, 0.3);
}

.login-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.form-footer {
  text-align: center;
  margin-top: 10px;
}

.create-admin-btn {
  width: 100%;
  padding: 12px;
  background: white;
  color: #667eea;
  border: 2px solid #667eea;
  border-radius: 12px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.create-admin-btn:hover:not(:disabled) {
  background: #f8f9ff;
  transform: translateY(-1px);
}

.create-admin-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.system-info {
  text-align: center;
  margin-top: auto;
  padding-top: 20px;
  border-top: 1px solid #e9ecef;
}

.system-info p {
  margin: 4px 0;
  font-size: 12px;
  color: #6c757d;
}

/* 帮助模态框 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2000;
  backdrop-filter: blur(3px);
}

.modal-content {
  background: white;
  border-radius: 16px;
  width: 90%;
  max-width: 500px;
  max-height: 90vh;
  overflow: hidden;
  box-shadow: 0 25px 80px rgba(0, 0, 0, 0.3);
  animation: modalSlideIn 0.3s ease-out;
}

@keyframes modalSlideIn {
  from {
    opacity: 0;
    transform: translateY(-30px) scale(0.95);
  }
  to {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 25px;
  border-bottom: 1px solid #e9ecef;
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: white;
}

.modal-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 8px;
}

.modal-close {
  background: none;
  border: none;
  color: white;
  font-size: 20px;
  cursor: pointer;
  padding: 5px;
  border-radius: 50%;
  transition: all 0.3s ease;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.modal-close:hover {
  background: rgba(255, 255, 255, 0.2);
}

.modal-body {
  padding: 25px;
  max-height: 60vh;
  overflow-y: auto;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding: 20px 25px;
  border-top: 1px solid #e9ecef;
  background: #f8f9fa;
}

.help-content h4 {
  color: #2c3e50;
  font-size: 16px;
  margin: 0 0 10px 0;
  font-weight: 600;
}

.help-content p {
  color: #6c757d;
  margin: 0 0 20px 0;
  line-height: 1.6;
}

.account-info {
  background: #f8f9fa;
  padding: 15px;
  border-radius: 8px;
  border-left: 4px solid #667eea;
  margin-bottom: 20px;
}

.account-info p {
  margin: 5px 0;
  font-family: 'Courier New', monospace;
}

.btn {
  padding: 10px 20px;
  border: none;
  border-radius: 8px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
}

.btn-primary {
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: white;
}

.btn-primary:hover:not(:disabled) {
  transform: translateY(-1px);
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
}

.btn-primary:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.btn-secondary {
  padding: 10px 20px;
  border: 2px solid #dee2e6;
  border-radius: 8px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  background: white;
  color: #6c757d;
}

.btn-secondary:hover:not(:disabled) {
  background: #f8f9fa;
  border-color: #adb5bd;
}

.btn-secondary:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.create-admin-form .form-group {
  margin-bottom: 16px;
}

.create-admin-form .form-group:last-child {
  margin-bottom: 0;
}

.create-admin-form label {
  display: block;
  margin-bottom: 6px;
  font-weight: 600;
  color: #495057;
  font-size: 14px;
}

.radio-group {
  display: flex;
  gap: 20px;
  margin-top: 5px;
}

.radio-label {
  display: flex;
  align-items: center;
  cursor: pointer;
  font-weight: 400 !important;
  font-size: 14px;
  color: #495057;
}

.radio-label input {
  margin-right: 6px;
  cursor: pointer;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .login-container {
    flex-direction: column;
    min-height: 100vh;
    border-radius: 0;
    margin: 0;
  }
  
  .login-background {
    order: 2;
    flex: none;
    padding: 40px 20px;
  }
  
  .login-form-container {
    order: 1;
    padding: 40px 20px;
  }
  
  .system-logo h1 {
    font-size: 24px;
  }
  
  .system-logo i {
    font-size: 48px;
  }
  
  .feature-list {
    grid-template-columns: 1fr;
    gap: 15px;
  }
  
  .help-links {
    flex-direction: column;
    gap: 10px;
  }
  
  .modal-content {
    width: 95%;
  }
}

@media (max-width: 480px) {
  .login-form-container {
    padding: 30px 15px;
  }
  
  .login-background {
    padding: 30px 15px;
  }
  
  .form-header h2 {
    font-size: 24px;
  }
}
</style>
